package com.example.springboot.Controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.excption.ServiceException;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import lombok.Builder;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能:
 * 作者：jian
 * 日期：2024/3/14 15:29
 * @CrossOrigin 解决跨域
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
@Builder
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 新增用户信息
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        System.out.println(user.getAvatar());
        try {
            if (StrUtil.isBlank(user.getAvatar())){
                user.setAvatar("http://localhost:8080/file/download/logo1.jpg");
            }

            userService.save(user);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误:username为唯一索引 DuplicateKeyException");
            } else {
                return Result.error("系统错误" + e);
            }
        }
        return Result.success(user);
    }

    /**
     * 查询所有用户信息
     *
     * @return
     */
    @GetMapping("/selectAll")
    public Result get() {
        List users = userService.list(new QueryWrapper<User>().orderByDesc("id"));//select * from user order by id desc
        return Result.success(users);
    }


    /**
     * 根据用户id查询用户信息
     *
     * @param id
     * @return
     */
    //json数据传 {"id"="2"}
    @GetMapping("/get/{id}")
    public Result getUser(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    /**
     * 根据id更改用户信息
     *
     * @param user
     * @return
     */
    //json数据传对象{"username":"lijain","name":"lisi","phone":"12354585546"}
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        System.out.println(user);
        userService.updateById(user);
        return Result.success();
    }

    /**
     * 根据id删除用户数据
     *User user = userService.getById(id);
     *         String role = user.getRole();
     *         if (role.equals("管理员")){
     *             return Result.error("无权限删除管理员");
     *         }else {
     *            userService.removeById(id);
     *             return Result.success();
     *         }
     * @param id
     * @return
     */

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        User currentUser = TokenUtils.getCurrentUser();
        if (id.equals(currentUser.getId())){
            throw new ServiceException("不能删除当前的用户");
        }
         userService.removeById(id);
         return Result.success();
    }
//    http://localhost:8080/user/delete/46
    //json 数据传数组[1,2]
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {

        for (Integer id:ids) {
            User user = userService.getById(id);
            String role = user.getRole();
            if (role.equals("管理员")){
                return Result.error("所含内容包含管理员，无法删除");
            }
        }
        userService.removeBatchByIds(ids);
        return Result.success();
    }

    //@RequestParam  url 参数 http://localhost:8080/user/getmore?username=91&name=马姐姐
//    @GetMapping("/getmore")
//    public Result getmore(@RequestParam String username, @RequestParam String name) {
//        List<User> users = userService.findUserByMore(username, name);
//        return Result.success(users);
//    }

    //多条件模糊查寻
//    @GetMapping("/getmo")
//    public Result getmo(@RequestParam String username, @RequestParam String name) {
//        List<User> users = userService.selectMo(username, name);
//        return Result.success(users);
//    }

    //多条件模糊查寻

    /**
     * 模糊查询分页
     * @param pageNum  当前页码
     * @param pageSize 每页有多少个
     * @param username
     * @param name
     * @return
     */
    @GetMapping("/selectByPage")
    public Result getPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam String username,
            @RequestParam String name) {

        QueryWrapper<User> queryWrapper =new  QueryWrapper<User>().orderByDesc("id");//默认倒叙
//       QueryWrapper<User> uSerQueryWrapper = new QueryWrapper<User>();
//       QueryWrapper<User> queryWrapper1 = queryWrapper.orderByDesc("id");

        //条件构造器模糊查询

        queryWrapper.like(StrUtil.isNotBlank(username),"username",username);
        queryWrapper.like(StrUtil.isNotBlank(name),"name",name);
        //select * from user where like '%#{username}%' and name like '%#{name}%'

        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);


        return Result.success(page);
    }

    /**
     * 批量到处数据
     */
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String ids,  //   1,2,3,4,5
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);

        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(ids)) {     // ["1", "2", "3"]   => [1,2,3]
            List<Integer> idsArr1 = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
            queryWrapper.in("id", idsArr1);
        } else {
            // 第一种全部导出或者条件导出
            queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        }
        list = userService.list(queryWrapper);   // 查询出当前User表的所有数据
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }

    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<User> userList = reader.readAll(User.class);
        // 写入数据到数据库
        try {
            userService.saveBatch(userList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("数据批量导入错误");
        }
        return Result.success();
    }


}